package com.darren.archive.consumer1.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.darren.archive.consumer1.sentinel.EchoControllerHandler;
import com.darren.archive.consumer1.service.EchoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Random;
import java.util.logging.Logger;

@RestController
public class EchoController {

    Logger logger = Logger.getLogger(EchoController.class.getName());

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private EchoService echoService;


    @Value("${spring.application.name}")
    private String appName;

    @GetMapping("/echo-consumer/app-name")
    @SentinelResource(value = "echo-consumer", blockHandler = "echoAppNameHandler", fallback = "echoAppNameFallback", blockHandlerClass = EchoControllerHandler.class, fallbackClass = EchoControllerHandler.class)
    public String echoAppName() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider");
        String url = String.format("http://%s/echo/%s",serviceInstance.getServiceId(), appName);
        System.out.println(url);
        int i = new Random().nextInt(100);
        if(i%2 == 0){
            logger.info(String.format("error:%s", Integer.parseInt("123a")));
        }
        return restTemplate.getForObject(url, String.class);
    }




    @GetMapping("/echo-feign/app-name")
    public String echoAppName2() {
        return echoService.echo(appName);
    }





}
